package com.growthsee.rider.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.growthsee.common.core.controller.BaseController;
import com.growthsee.common.core.domain.AjaxResult;
import com.growthsee.common.core.page.TableDataInfo;
import com.growthsee.common.utils.SecurityUtils;
import com.growthsee.rider.domain.RiderAddAction;
import com.growthsee.rider.domain.RiderCourse;
import com.growthsee.rider.domain.RiderInfo;
import com.growthsee.rider.enumeration.CourseTypeEnum;
import com.growthsee.rider.enumeration.YesNoEnum;
import com.growthsee.rider.param.RiderAddActionParam;
import com.growthsee.rider.service.RiderAddActionService;
import com.growthsee.rider.service.RiderCourseService;
import com.growthsee.rider.service.RiderInfoService;
import com.growthsee.rider.utils.ApplicationContexts;
import com.growthsee.rider.wrapper.RiderAddActionWrapper;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author csy
 * @since 2021-05-13
 */
@RestController
@RequestMapping("rider/addAction")
@AllArgsConstructor
@Api("消分记录")
public class RiderAddActionController extends BaseController {
    private final RiderAddActionService riderAddActionService;
    private final RiderCourseService riderCourseService;
    private final RiderInfoService riderInfoService;
    @GetMapping
    public TableDataInfo query(RiderAddActionParam riderAddActionParam) {
        startPage();
        if(StringUtils.isNotEmpty(riderAddActionParam.getUserId())){
            RiderInfo riderInfo =riderInfoService.getOne(Wrappers.<RiderInfo>lambdaQuery().eq(RiderInfo::getId,riderAddActionParam.getUserId()));
            if(ObjectUtils.isNotEmpty(riderInfo))riderAddActionParam.setUserId(riderInfo.getUserId());
        }
        LambdaQueryWrapper<RiderAddAction> queryWrapper = RiderAddActionWrapper.builder().getQuery(riderAddActionParam);
        List list = riderAddActionService.list(queryWrapper);
        return getDataTable(list);
    }



    @PostMapping(value = "{courseId}")
    public AjaxResult insert(@PathVariable String courseId) {
        RiderCourse course =riderCourseService.getById(courseId);
        if(course.getType()== CourseTypeEnum.PAPER.getValue()){
            RiderInfoService riderInfoService = ApplicationContexts.getBean(RiderInfoService.class);
            riderInfoService.update(Wrappers.<RiderInfo>lambdaUpdate()
                    .set(RiderInfo::getPassed, YesNoEnum.YES.getValue())
                    .eq(RiderInfo::getUserId, SecurityUtils.getLoginUser().getUser().getUserId()));
        }else {
            riderAddActionService.addAction(courseId);
        }
        return AjaxResult.success();
    }

}

